package com.techysky.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.techysky.entity.MaintPlan;
import com.techysky.repository.MaintPlanRepository;
import com.techysky.repository.MaintRecordRepository;
import com.techysky.service.MaintService;

@Service("maintService")
public class MaintServiceImpl implements MaintService{
	private static final Log log=LogFactory.getLog(MaintServiceImpl.class);
	@Autowired
	private transient MaintPlanRepository maintPlanRepository;
	@Autowired
	private transient MaintRecordRepository maintRecordRepository;
	
	@Override
	public Map getWwctj(){
		Map map=new HashMap<>();
		int ywplans = 0;
		int wwplans = 0;
		int jgdays=0;
		List<MaintPlan> yplans = maintPlanRepository.findAll1();
		String systemTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date()); 
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		for (MaintPlan maintPlan : yplans) {
			String startime=maintPlan.getCreateDate();
			String jg=maintPlan.getLimitCond();
		if(!StringUtils.isBlank(startime)&&!"0".equals(jg.substring(0,jg.length()-1))&&jg.substring(0,jg.length()-1).matches("[0-9]+")){
	         try {
	        	Date date2 = format.parse(systemTime);
				Date date1 = format.parse(startime);
				int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));//实际间隔
				String jg1=jg.substring(jg.length()-1);//间隔单位
				String jg2=jg.substring(0,jg.length()-1);//间隔数
				//间隔天数
				if("天".equals(jg1)){
					jgdays=Integer.parseInt(jg2);
				}else if("月".equals(jg1)){
					jgdays=Integer.parseInt(jg2)*30;
				}else if("年".equals(jg1)){
					jgdays=Integer.parseInt(jg2)*365;
				}
				//取整
				int zheng=days/jgdays;
				//取余
				int yu=days%jgdays;
				//当前周期开始时间
				String endStDate = startime;
				Calendar ca = Calendar.getInstance();
				 ca.setTime(date1);
				if(yu==0&&zheng<=1){
					endStDate = startime;
				}else if(yu==0&&zheng>1){
					ca.add(Calendar.DATE, (zheng-1)*jgdays);
					date1 = ca.getTime();
					endStDate = format.format(date1);
				}else{
					ca.add(Calendar.DATE, zheng*jgdays);
					date1 = ca.getTime();
					endStDate = format.format(date1);
				}
				
				int mRecords = maintRecordRepository.findMaintRecord(endStDate,systemTime,maintPlan.getId());
				if(mRecords>0){
					ywplans++;
				}else{
					wwplans++;
				}
			} catch (ParseException e) {
				log.info(e);
			}
		}
		}
		map.put("wwc", wwplans);
		map.put("ywc", ywplans);
		return map;
	}	
	

}
